﻿@using BootstrapBlazor.Components
@using System.Text.Json

<div class="mt-3">
    <Button OnClick="Success">@Localizer["NormalButtonText1"]</Button>
    <Button OnClick="Fail">@Localizer["NormalButtonText2"]</Button>
    @if (!string.IsNullOrEmpty(ResultMessage))
    {
        <div class="mt-2"><code>@ResultMessage</code></div>
    }
</div>

@code
{
    private string? ResultMessage { get; set; }

    [Inject]
    [NotNull]
    private IStringLocalizer<AjaxNormal>? Localizer { get; set; }

    [Inject]
    [NotNull]
    private AjaxService? AjaxService { get; set; }

    [Inject]
    [NotNull]
    private SwalService? SwalService { get; set; }

    private Task Success() => ProcessResponse("admin", "123456");

    private Task Fail() => ProcessResponse("admin", "123");

    private async Task ProcessResponse(string userName, string password)
    {
        var option = new AjaxOption()
        {
            Url = "/api/Login",
            Data = new User() { UserName = userName, Password = password }
        };
        var result = await AjaxService.InvokeAsync(option);
        if (result == null)
        {
            ResultMessage = "Login failed";
        }
        else
        {
            if (200 == result.RootElement.GetProperty("code").GetInt32())
            {
                await SwalService.Show(new SwalOption() { Content = "Login success！", Category = SwalCategory.Success });
            }
            else
            {
                await SwalService.Show(new SwalOption() { Content = $"Login failed: {result.RootElement.GetProperty("message").GetString()}", Category = SwalCategory.Error });
            }
        }
    }

    class User
    {
        public string? UserName { get; set; }

        public string? Password { get; set; }
    }
}
